#include "dockwidget2.h"
#include "ui_dockwidget2.h"
#include <QDebug>
#include <QTableWidget>
#include <QTableView>
#include <QHeaderView>
#include <QMutex>
#include <QFile>
#include <QFileDialog>
#include <QDateTime>
#include <QSettings>
#include <overflawtimes.h>
#include <QThread>
#include <QMessageBox>
DockWidgets dockWidgets;
extern QMutex Locker;
extern QString saveFileName;
extern int saveDataCount;
QDateTime saveDateTime;
bool firstFlag=true;                                //首次存文件
#define MAX_NUMBER_OF_OVERFLAW 10
DockWidget2::DockWidget2(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DockWidget2)
{
    ui->setupUi(this);
    SlotInit();
    setWindowFlags(Qt::WindowStaysOnTopHint);

}

DockWidget2::~DockWidget2()
{
    delete ui;
}


void DockWidget2::SlotInit()
{
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(SetTableWidget()));
    connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(LoadFile()));
    connect(this,SIGNAL(To_ShowRecv(RecvBuf,QByteArray,QByteArray,long)),this,SLOT(ShowRecv(RecvBuf,QByteArray,QByteArray,long)));
}

void DockWidget2::SetTableWigetByRow(int rowValue)
{
    SetTableWidget1(rowValue);
    SetTableWidget2(rowValue);
    SetTableWidget3(rowValue);
    SetTableWidget4(rowValue);
}

void DockWidget2::SetTableWidget1(int rowValue)
{
    if(rowValue>=1&&rowValue<=32)
    {
        if(tableWidget[0]==nullptr)
        {
            tableWidget[0]=new QTableWidget(this);
        }
        tableWidget[0]->clear();
        tableWidget[0]->setGeometry(20,68,421,671);
        tableWidget[0]->setRowCount(rowValue);
        tableWidget[0]->setColumnCount(7);
        // 设置表头
        QStringList headers;
        headers << "序号" << "寄存器"<<"数据名称"<<"数据"<<"最小值"<<"最大值"<<"超过次数";
        tableWidget[0]->setHorizontalHeaderLabels(headers);

        tableWidget[0]->horizontalHeader()->setDefaultSectionSize(58);
        tableWidget[0]->verticalHeader()->setMinimumSectionSize(15);
        tableWidget[0]->verticalHeader()->setDefaultSectionSize(20);
        tableWidget[0]->verticalHeader()->setVisible(false);
        tableWidget[0]->show();

        connect(tableWidget[0],SIGNAL(cellDoubleClicked(int, int)),this,SLOT(ShowOverFlawTimes(int,int)));
    }
    else if(rowValue>=33)
    {
        if(tableWidget[0]==nullptr)
        {
            tableWidget[0]=new QTableWidget(this);
        }
        tableWidget[0]->clear();
        tableWidget[0]->setGeometry(20,68,421,671);
        tableWidget[0]->setRowCount(32);
        tableWidget[0]->setColumnCount(7);
        // 设置表头
        QStringList headers;
        headers << "序号" << "寄存器"<<"数据名称"<<"数据"<<"最小值"<<"最大值"<<"超过次数";
        tableWidget[0]->setHorizontalHeaderLabels(headers);

        tableWidget[0]->horizontalHeader()->setDefaultSectionSize(58);
        tableWidget[0]->verticalHeader()->setMinimumSectionSize(15);
        tableWidget[0]->verticalHeader()->setDefaultSectionSize(20);
        tableWidget[0]->verticalHeader()->setVisible(false);
        tableWidget[0]->show();

        connect(tableWidget[0],SIGNAL(cellDoubleClicked(int, int)),this,SLOT(ShowOverFlawTimes(int,int)));
    }
}

void DockWidget2::SetTableWidget2(int rowValue)
{
    if(rowValue>=33&&rowValue<=64)
    {
        if(tableWidget[1]==nullptr)
        {
            tableWidget[1]=new QTableWidget(this);
        }

        tableWidget[1]->clear();
        tableWidget[1]->setGeometry(20+421+8,68,421,671);
        tableWidget[1]->setRowCount(rowValue-32);
        tableWidget[1]->setColumnCount(7);
        // 设置表头
        QStringList headers;
        headers << "序号" << "寄存器"<<"数据名称"<<"数据"<<"最小值"<<"最大值"<<"超过次数";
        tableWidget[1]->setHorizontalHeaderLabels(headers);

        tableWidget[1]->horizontalHeader()->setDefaultSectionSize(58);
        tableWidget[1]->verticalHeader()->setMinimumSectionSize(15);
        tableWidget[1]->verticalHeader()->setDefaultSectionSize(20);
        tableWidget[1]->verticalHeader()->setVisible(false);
        tableWidget[1]->show();
        connect(tableWidget[1],SIGNAL(cellDoubleClicked(int, int)),this,SLOT(ShowOverFlawTimes2(int,int)));

    }
    else if(rowValue>=65)
    {
        if(tableWidget[1]==nullptr)
        {
            tableWidget[1]=new QTableWidget(this);
        }
        tableWidget[1]->clear();
        tableWidget[1]->setGeometry(20+421+8,68,421,671);
        tableWidget[1]->setRowCount(32);
        tableWidget[1]->setColumnCount(7);
        // 设置表头
        QStringList headers;
        headers << "序号" << "寄存器"<<"数据名称"<<"数据"<<"最小值"<<"最大值"<<"超过次数";
        tableWidget[1]->setHorizontalHeaderLabels(headers);

        tableWidget[1]->horizontalHeader()->setDefaultSectionSize(58);
        tableWidget[1]->verticalHeader()->setMinimumSectionSize(15);
        tableWidget[1]->verticalHeader()->setDefaultSectionSize(20);
        tableWidget[1]->verticalHeader()->setVisible(false);
        tableWidget[1]->show();
        connect(tableWidget[1],SIGNAL(cellDoubleClicked(int, int)),this,SLOT(ShowOverFlawTimes2(int,int)));
    }
}

void DockWidget2::SetTableWidget3(int rowValue)
{
    if(rowValue>=65&&rowValue<=96)
    {
        if(tableWidget[2]==nullptr)
        {
            tableWidget[2]=new QTableWidget(this);
        }
        tableWidget[2]->clear();
        tableWidget[2]->setGeometry(20+421+8+421+8,68,421,671);
        tableWidget[2]->setRowCount(rowValue-64);
        tableWidget[2]->setColumnCount(7);
        // 设置表头
        QStringList headers;
        headers << "序号" << "寄存器"<<"数据名称"<<"数据"<<"最小值"<<"最大值"<<"超过次数";
        tableWidget[2]->setHorizontalHeaderLabels(headers);

        tableWidget[2]->horizontalHeader()->setDefaultSectionSize(58);
        tableWidget[2]->verticalHeader()->setMinimumSectionSize(15);
        tableWidget[2]->verticalHeader()->setDefaultSectionSize(20);
        tableWidget[2]->verticalHeader()->setVisible(false);
        tableWidget[2]->show();
        connect(tableWidget[2],SIGNAL(cellDoubleClicked(int, int)),this,SLOT(ShowOverFlawTimes3(int,int)));

    }
    else if(rowValue>=97)
    {
        if(tableWidget[2]==nullptr)
        {
            tableWidget[2]=new QTableWidget(this);
        }
        tableWidget[2]->clear();
        tableWidget[2]->setGeometry(20+421+8+421+8,68,421,671);
        tableWidget[2]->setRowCount(32);
        tableWidget[2]->setColumnCount(7);
        // 设置表头
        QStringList headers;
        headers << "序号" << "寄存器"<<"数据名称"<<"数据"<<"最小值"<<"最大值"<<"超过次数";
        tableWidget[2]->setHorizontalHeaderLabels(headers);

        tableWidget[2]->horizontalHeader()->setDefaultSectionSize(58);
        tableWidget[2]->verticalHeader()->setMinimumSectionSize(15);
        tableWidget[2]->verticalHeader()->setDefaultSectionSize(20);
        tableWidget[2]->verticalHeader()->setVisible(false);
        tableWidget[2]->show();
        connect(tableWidget[2],SIGNAL(cellDoubleClicked(int, int)),this,SLOT(ShowOverFlawTimes3(int,int)));

    }
}

void DockWidget2::SetTableWidget4(int rowValue)
{
    if(rowValue>=96&&rowValue<=128)
    {
        if(tableWidget[3]==nullptr)
        {
            tableWidget[3]=new QTableWidget(this);
        }
        tableWidget[3]->clear();
        tableWidget[3]->setGeometry(20+421+8+421+8+421+8,68,421,671);
        tableWidget[3]->setRowCount(rowValue-96);
        tableWidget[3]->setColumnCount(7);
        // 设置表头
        QStringList headers;
        headers << "序号" << "寄存器"<<"数据名称"<<"数据"<<"最小值"<<"最大值"<<"超过次数";
        tableWidget[3]->setHorizontalHeaderLabels(headers);

        tableWidget[3]->horizontalHeader()->setDefaultSectionSize(58);
        tableWidget[3]->verticalHeader()->setMinimumSectionSize(15);
        tableWidget[3]->verticalHeader()->setDefaultSectionSize(20);
        tableWidget[3]->verticalHeader()->setVisible(false);
        tableWidget[3]->show();
        connect(tableWidget[3],SIGNAL(cellDoubleClicked(int, int)),this,SLOT(ShowOverFlawTimes4(int,int)));

    }
    else if(rowValue==128)
    {
        if(tableWidget[3]==nullptr)
        {
            tableWidget[3]=new QTableWidget(this);
        }
        tableWidget[3]->clear();
        tableWidget[3]->setGeometry(20+421+8+421+8+421+8,68,421,671);
        tableWidget[3]->setRowCount(32);
        tableWidget[3]->setColumnCount(7);
        // 设置表头
        QStringList headers;
        headers << "序号" << "寄存器"<<"数据名称"<<"数据"<<"最小值"<<"最大值"<<"超过次数";
        tableWidget[3]->setHorizontalHeaderLabels(headers);

        tableWidget[3]->horizontalHeader()->setDefaultSectionSize(58);
        tableWidget[3]->verticalHeader()->setMinimumSectionSize(15);
        tableWidget[3]->verticalHeader()->setDefaultSectionSize(20);
        tableWidget[3]->verticalHeader()->setVisible(false);
        tableWidget[3]->show();
        connect(tableWidget[3],SIGNAL(cellDoubleClicked(int, int)),this,SLOT(ShowOverFlawTimes4(int,int)));

    }
}

void DockWidget2::InitTableWidgetItem(int rowValue)
{
    if(rowValue<=32)
    {
        for(int i=0;i<=tableWidget[0]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[0]->columnCount()-1;j++)
            {
                tableWidget[0]->setItem(i,j,new QTableWidgetItem());
            }
        }
    }

    if(rowValue>=33&&rowValue<=64)
    {
        for(int i=0;i<=tableWidget[0]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[0]->columnCount()-1;j++)
            {
                tableWidget[0]->setItem(i,j,new QTableWidgetItem());
            }
        }
        for(int i=0;i<=tableWidget[1]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[1]->columnCount()-1;j++)
            {
                tableWidget[1]->setItem(i,j,new QTableWidgetItem());
            }
        }

    }

    if(rowValue>=65&&rowValue<=96)
    {
        for(int i=0;i<=tableWidget[0]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[0]->columnCount()-1;j++)
            {
                tableWidget[0]->setItem(i,j,new QTableWidgetItem());
            }
        }
        for(int i=0;i<=tableWidget[1]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[1]->columnCount()-1;j++)
            {
                tableWidget[1]->setItem(i,j,new QTableWidgetItem());
            }
        }
        for(int i=0;i<=tableWidget[2]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[2]->columnCount()-1;j++)
            {
                tableWidget[2]->setItem(i,j,new QTableWidgetItem());
            }
        }
    }

    if(rowValue>=97&&rowValue<=128)
    {
        for(int i=0;i<=tableWidget[0]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[0]->columnCount()-1;j++)
            {
                tableWidget[0]->setItem(i,j,new QTableWidgetItem());
            }
        }
        for(int i=0;i<=tableWidget[1]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[1]->columnCount()-1;j++)
            {
                tableWidget[1]->setItem(i,j,new QTableWidgetItem());
            }
        }
        for(int i=0;i<=tableWidget[2]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[2]->columnCount()-1;j++)
            {
                tableWidget[2]->setItem(i,j,new QTableWidgetItem());
            }
        }

        for(int i=0;i<=tableWidget[3]->rowCount()-1;i++)
        {
            for(int j=0;j<=tableWidget[3]->columnCount()-1;j++)
            {
                tableWidget[3]->setItem(i,j,new QTableWidgetItem());
            }
        }

    }
}

void DockWidget2::InitTableWidgetText(int rowValue)
{
    if(rowValue<=32)
    {
        for (int i=0;i<=tableWidget[0]->rowCount()-1;i++)
        {
            tableWidget[0]->item(i,0)->setText(QString::number(i+1));
            tableWidget[0]->item(i,1)->setText(QString::number(i+registerStart,10));
        }
    }
    if(rowValue>=33&&rowValue<=64)
    {
        for (int i=0;i<=tableWidget[0]->rowCount()-1;i++)
        {
            tableWidget[0]->item(i,0)->setText(QString::number(i+1));
            tableWidget[0]->item(i,1)->setText(QString::number(i+registerStart,10));
        }
        for (int i=0;i<=tableWidget[1]->rowCount()-1;i++)
        {
            tableWidget[1]->item(i,0)->setText(QString::number(i+1+32));
            tableWidget[1]->item(i,1)->setText(QString::number(i+registerStart+32,10));
        }
    }

    if(rowValue>=65&&rowValue<=96)
    {

        for (int i=0;i<=tableWidget[0]->rowCount()-1;i++)
        {
            tableWidget[0]->item(i,0)->setText(QString::number(i+1));
            tableWidget[0]->item(i,1)->setText(QString::number(i+registerStart,10));
        }
        for (int i=0;i<=tableWidget[1]->rowCount()-1;i++)
        {
            tableWidget[1]->item(i,0)->setText(QString::number(i+1+32));
            tableWidget[1]->item(i,1)->setText(QString::number(i+registerStart+32,10));
        }
        for (int i=0;i<=tableWidget[2]->rowCount()-1;i++)
        {
            tableWidget[2]->item(i,0)->setText(QString::number(i+1+64));
            tableWidget[2]->item(i,1)->setText(QString::number(i+registerStart+64,10));
        }
    }
    if(rowValue>=97&&rowValue<=128)
    {
        for (int i=0;i<=tableWidget[0]->rowCount()-1;i++)
        {
            tableWidget[0]->item(i,0)->setText(QString::number(i+1));
            tableWidget[0]->item(i,1)->setText(QString::number(i+registerStart,10));
        }
        for (int i=0;i<=tableWidget[1]->rowCount()-1;i++)
        {
            tableWidget[1]->item(i,0)->setText(QString::number(i+1+32));
            tableWidget[1]->item(i,1)->setText(QString::number(i+registerStart+32,10));
        }
        for (int i=0;i<=tableWidget[2]->rowCount()-1;i++)
        {
            tableWidget[2]->item(i,0)->setText(QString::number(i+1+64));
            tableWidget[2]->item(i,1)->setText(QString::number(i+registerStart+64,10));
        }
        for (int i=0;i<=tableWidget[3]->rowCount()-1;i++)
        {
            tableWidget[3]->item(i,0)->setText(QString::number(i+1+96));
            tableWidget[3]->item(i,1)->setText(QString::number(i+registerStart+96,10));
        }
    }

}

void DockWidget2::UIInit()
{
    if(tableWidget[0]!=nullptr)
    {
        tableWidget[0]->clear();
        delete tableWidget[0];
        tableWidget[0]=nullptr;
    }

    if(tableWidget[1]!=nullptr)
    {
        tableWidget[1]->clear();
        delete tableWidget[1];
        tableWidget[1]=nullptr;
    }

    if(tableWidget[2]!=nullptr)
    {
        tableWidget[2]->clear();
        delete tableWidget[2];
        tableWidget[2]=nullptr;
    }

    if(tableWidget[3]!=nullptr)
    {
        tableWidget[3]->clear();
        delete tableWidget[3];
        tableWidget[3]=nullptr;
    }
}


QTableWidgetItem *DockWidget2::GetItem(int index, int column)
{
    QTableWidgetItem *itemPtr=nullptr;

    if(index<=31)
    {
        if(tableWidget[0]==nullptr)
            return nullptr;
        itemPtr=tableWidget[0]->item(index,column);
    }
    if(index>=32&&index<=63)
    {
        if(tableWidget[1]==nullptr)
            return nullptr;

        itemPtr=tableWidget[1]->item(index-32,column);
    }
    if(index>=64&&index<=95)
    {
        if(tableWidget[2]==nullptr)
            return nullptr;
        itemPtr=tableWidget[2]->item(index-64,column);
    }
    if(index>=96&&index<=124)
    {
        if(tableWidget[3]==nullptr)
            return nullptr;

        itemPtr=tableWidget[3]->item(index-96,column);
    }
    return itemPtr;
}

void DockWidget2::UpdateSendFrame()
{
    sendFrameCount++;
    //ui->textEdit->setText(QString("发送次数=%0,接收正确次数=%1，轮询时间=%2").arg(sendFrameCount).arg(recvFrameCount));
}

void DockWidget2::UpdateRecvFrame()
{
    recvFrameCount++;
    //ui->textEdit->setText(QString("发送次数=%0,接收正确次数=%1，轮询时间=%2").arg(sendFrameCount).arg(recvFrameCount));
}


void DockWidget2::CreateFolder()
{
    qDebug()<<QCoreApplication::applicationDirPath();
}

void DockWidget2::GetSaveFileName()
{
    QDateTime time=QDateTime::currentDateTime();
    QString date=time.toString("yyyyMMdd");
    QDir dir(QCoreApplication::applicationDirPath()+"/数据存储/"+date);
    dir.mkpath(QCoreApplication::applicationDirPath()+"/数据存储/"+date);
    QSettings set("SaveData.ini",QSettings::IniFormat);
    set.beginGroup("Value");
    QString datatime=set.value("date","").toString();
    if(datatime==date)
    {
        count=set.value("count").toInt();
        count++;
        set.setValue("count",count);
    }
    else
    {
        count=1;
        set.setValue("count",count);
        set.setValue("date",date);
    }
    set.endGroup();
    QString filename=date+QString::number(count).sprintf("%02d", count);
    saveFileName=QCoreApplication::applicationDirPath()+"/数据存储/"+date+"/"+filename+".txt";
    qDebug()<<saveFileName;
}

void DockWidget2::SaveFile(QByteArray send, QByteArray recv)
{
    QString timeStr=saveDateTime.toString("yyyy-MM-dd hh:mm:ss");
    QString sendStr=timeStr+"Send:"+send.toHex()+"\r\n";
    QString recvStr=timeStr+"Recv:"+recv.toHex()+"\r\n";
    QFile f;
    f.setFileName(saveFileName);
    if(f.open(QFile::ReadWrite|QFile::Append))
    {
        f.write(sendStr.toStdString().c_str());
        f.write(recvStr.toStdString().c_str());
        f.close();
    }
}

void DockWidget2::UpdateOverFlawTime(int i,QByteArray recvDataSave)
{
    Q_UNUSED(recvDataSave);
    if(dataUI.row[i].overflowDateTimeCount<MAX_NUMBER_OF_OVERFLAW)
    {
        dataUI.row[i].overflowDateTime[dataUI.row[i].overflowDateTimeCount]=saveDateTime;
        dataUI.row[i].overflowDateTimeCount++;
    }
    overFlawTime.UpDate();
}

void DockWidget2::SaveOverFlawLog(int i, QByteArray recv,QDateTime date)
{
    QString dateStr=date.toString("yyyy_MM_dd_");
    QString dateStr2=date.toString("yyyyMMdd");
    //QString DAT
    QString fileRoute="";
    fileRoute=QApplication::applicationDirPath()+"/数据存储/数据报警/"+dateStr2+"/"+dateStr+QString("%0/").arg(overflawFolderCount);
    QDir dir(fileRoute);
    dir.mkpath(fileRoute);

    QFile file;
    file.setFileName(fileRoute+QString("寄存器%0.txt").arg(i+registerStart));
    if(file.open(QFile::ReadWrite|QFile::Append))
    {
        QString writeContent;
        writeContent="报警时间:"+date.toString("yyyy-MM-dd hh:mm:ss,报警原始数据")+recv.toHex()+"\r\n";
        file.write(writeContent.toStdString().c_str());
        file.close();
    }
    // QString filem
}

int DockWidget2::GetWaringFolderCount()
{
    int ret=0;
    QSettings set("SaveData.ini",QSettings::IniFormat);
    set.beginGroup("Value");

    QDateTime currentDate;
    currentDate=QDateTime::currentDateTime();
    QString currentDataStr=currentDate.toString("yyyyMMdd");

    QString readCurrentData=set.value("WarningDate","0").toString();
    if(readCurrentData!=currentDataStr)
    {
        set.setValue("WarningDate",currentDataStr);
        set.setValue("WarningCount",1);
        set.endGroup();
        ret=1;
        return ret;
    }
    else
    {
        ret=set.value("WarningCount",0).toInt();
        ret++;
        set.setValue("WarningCount",ret);
        set.endGroup();
        return ret;
    }
}

void DockWidget2::Handle16bitStype(int i,RecvBuf value,QByteArray recvData)
{


    //获取值
    //qDebug()<<"显示单元格"<<__LINE__;
    short showValue=value.recvBuf[i];
    //乘以k
    float realValue=(float)showValue*dataUI.row[i].k;
    //显示
    // qDebug()<<"显示单元格"<<__LINE__;
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
        item->setText(QString::number(realValue));
    // qDebug()<<"显示单元格"<<__LINE__;
    //获取min,max
    short min=0,max=0;
    item=GetItem(i,4);
    if(item!=nullptr)
    {
        min=item->text().toDouble();
    }
    else
    {
//        QMessageBox a;
//        a.setText("min failed");
//        a.show();
//        a.exec();

    }

    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();
    else
    {
//        QMessageBox a;
//        a.setText("max failed");
//        a.show();
//        a.exec();
    }
    //判断范围
    if(realValue<min||realValue>max)
    {
//        {
//            QMessageBox a;
//            a.setText(QString::number(min)+"min"+QString::number(max)+"max"+QString::number(realValue));
//            a.show();
//            a.exec();
//        }
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);
    }
    else
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }

    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));



}

void DockWidget2::Handle16bitUtype(int i, RecvBuf value, QByteArray recvData)
{
    //获取值
    ushort showValue=value.recvBuf[i];
    //乘以k
    float realValue=(float)showValue*dataUI.row[i].k;
    //显示
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
        item->setText(QString::number(realValue));
    //获取min,max
    ushort min=0,max=0;
    item=GetItem(i,4);
    if(item!=nullptr)
        min=item->text().toDouble();

    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();
    //判断范围
    if(realValue<min||realValue>max)
    {

        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);
    }
    else
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }

    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));
}

void DockWidget2::Handle16bitXorBType(int i, RecvBuf value, QByteArray recvData)
{
    //获取值
    ushort showValue=value.recvBuf[i];
    //乘以k
    //float realValue=(float)showValue*dataUI.row[i].k;
    //显示
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
    {
        if(dataUI.row[i].type=="X")
            item->setText(QString::number(showValue,16).prepend("0x"));
        else
            item->setText(QString::number(showValue,2));
    }
    //获取min,max
    ushort min=0,max=0;

    item=GetItem(i,4);
    if(item!=nullptr)
        min=item->text().toDouble();
    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();

    if(showValue<min||showValue>max)
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);
    }
    else
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }

    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));
}

void DockWidget2::Handle32bitSType(int i, RecvBuf value, QByteArray recvData, uint32_t combine)
{
    Q_UNUSED(value);
    //获取值
    int32_t showValue=combine;
    //乘以斜率k
    float realValue=(double)showValue*dataUI.row[i].k;
    //显示
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
        item->setText(QString::number(realValue));
    //获取范围
    double min=0,max=0;
    item=GetItem(i,4);
    if(item!=nullptr)
        min=item->text().toDouble();
    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();

    if(realValue<min||realValue>max)
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;

        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);

    }
    else
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }
    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));

}

void DockWidget2::Handle32bitUType(int i, RecvBuf value, QByteArray recvData, uint32_t combine)
{
      Q_UNUSED(value);
    //获取值
    uint32_t showValue=combine;
    //乘以斜率k
    float realValue=(double)showValue*dataUI.row[i].k;
    //显示
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
        item->setText(QString::number(realValue));
    //获取范围
    double min=0,max=0;
    item=GetItem(i,4);
    if(item!=nullptr)
        min=item->text().toDouble();
    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();

    if(realValue<min||realValue>max)
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);

    }
    else
    {
        item=GetItem(i,3);

        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }
    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));
}

void DockWidget2::Handle32bitXorBType(int i, RecvBuf value, QByteArray recvData, uint32_t combine)
{
      Q_UNUSED(value);
    //获取值
    uint32_t showValue=combine;
    //显示
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
    {
        if(dataUI.row[i].type=="X")
            item->setText(QString::number(showValue,16));
        else if(dataUI.row[i].type=="B")
        {
            item->setText(QString::number(showValue,2));
        }
    }
    //获取范围
    double min=0,max=0;
    item=GetItem(i,4);
    if(item!=nullptr)
        min=item->text().toDouble();
    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();

    if(showValue<min||showValue>max)
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);

    }
    else
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }
    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));
}

void DockWidget2::Handle64bitSType(int i, RecvBuf value, QByteArray recvData, uint64_t combine)
{
      Q_UNUSED(value);
    //获取值
    int64_t showValue=combine;
    //乘以斜率
    double realValue=(double)showValue*dataUI.row[i].k;
    //显示
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
        item->setText(QString::number(realValue));
    //获取范围
    double min=0,max=0;
    item=GetItem(i,4);
    if(item!=nullptr)
        min=item->text().toDouble();
    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();

    if(realValue<min||realValue>max)
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);

    }
    else
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }
    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));
}

void DockWidget2::Handle64bitUType(int i, RecvBuf value, QByteArray recvData, uint64_t combine)
{
      Q_UNUSED(value);
    //获取值
    uint64_t showValue=combine;
    //乘以斜率k
    double realValue=(double)showValue*dataUI.row[i].k;
    //显示
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
        item->setText(QString::number(realValue));
    //获取范围
    double min=0,max=0;
    item=GetItem(i,4);
    if(item!=nullptr)
        min=item->text().toDouble();
    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();

    if(showValue<min||showValue>max)
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);
    }
    else
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }
    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));
}

void DockWidget2::Handle64bitXorBType(int i, RecvBuf value, QByteArray recvData, uint64_t combine)
{
      Q_UNUSED(value);
    //获取值
    uint64_t showValue=combine;
    //显示
    QTableWidgetItem *item=GetItem(i,3);
    if(item!=nullptr)
    {
        if(dataUI.row[i].type=="X")
            item->setText(QString::number(showValue,16).prepend("0x"));
        else if(dataUI.row[i].type=="B")
        {
            item->setText(QString::number(showValue,2));
        }
    }
    //获取范围
    double min=0,max=0;
    item=GetItem(i,4);
    if(item!=nullptr)
        min=item->text().toDouble();
    item=GetItem(i,5);
    if(item!=nullptr)
        max=item->text().toDouble();

    if(showValue<min||showValue>max)
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
        UpdateOverFlawTime(i,recvData);
        SaveOverFlawLog(i,recvData,saveDateTime);
    }
    else
    {
        item=GetItem(i,3);
        if(item!=nullptr)
            item->setBackgroundColor(Qt::white);
    }
    item=GetItem(i,6);
    if(item!=nullptr)
        item->setText(QString::number(dataUI.row[i].overflowTimes));
}

void DockWidget2::closeEvent(QCloseEvent *event)
{
      Q_UNUSED(event);
    qDebug()<<__FUNCTION__<<__LINE__<<dockWidgets.currentIDVector.count();
    //重新管理窗口
    for(int i=0;i<=127;i++)
    {
        if(dockWidgets.currentIDVector[i]==currentID)
        {
            Locker.lock();
            dockWidgets.currentIDVector.remove(i);
            dockWidgets.element[currentID].isInUse=false;
            Locker.unlock();
            qDebug()<<"释放"<<currentID<<dockWidgets.currentIDVector.count();
            break;
        }
    }
    //重新生成信号与槽
}

void DockWidget2::SetTableWidget()
{
    //emit CloseCommunitcation();
    //QThread::msleep(1000);
    qDebug()<<__FUNCTION__;

    //更新起始寄存器和寄存器数目
    registerStart=ui->spinBox->value();
    registerSum=ui->spinBox_2->value();
    SetTableWigetByRow(registerSum);
    InitTableWidgetItem(registerSum);
    InitTableWidgetText(registerSum);
}

QString DockWidget2::GetOriginalDataContent(QString data, int& value)
{
    if(data.contains("寄存器"))
    {
        value=1;
    }
    else if(data.contains("K"))
    {
        value=2;
    }
    else if(data.contains("TYPE"))
    {
        value=3;
    }
    else if(data.contains("BIT"))
    {
        value=4;
    }
    else if(data.contains("MIN"))
    {
        value=5;
    }
    else if(data.contains("MAX"))
    {
        value=6;
    }
    QString ret;
    ret=data.remove(0,data.indexOf('=')+1);
    return ret;
}

void DockWidget2::LoadFile()
{
    qDebug()<<__FUNCTION__<<__LINE__;
    QString fileName;
    fileName=QFileDialog::getOpenFileName();
    QFile file;
    file.setFileName(fileName);
    if(file.open(QFile::ReadOnly))
    {
        int atLine=0;
        while (!file.atEnd())
        {
            QByteArray read=file.readLine();
            QString readStr=read.toStdString().c_str();
            atLine++;
            if(atLine==1)
            {
                //起始值
                QString tmp=readStr;
                tmp=tmp.remove(0,tmp.indexOf('=')+1);
                tmp=tmp.remove(tmp.indexOf(','),tmp.length()-tmp.indexOf(','));
                dataUI.start=tmp.toInt();
                qDebug()<<tmp<<dataUI.start;
                //终点值
                tmp=readStr;
                tmp=tmp.remove(0,tmp.indexOf('=')+1);
                tmp=tmp.remove(0,tmp.indexOf('=')+1);
                tmp=tmp.remove(tmp.indexOf(','),tmp.length()-tmp.indexOf(','));
                dataUI.end=tmp.toInt();
                qDebug()<<tmp<<dataUI.end;
                //轮询时间
                tmp=readStr;
                tmp=tmp.remove(0,tmp.indexOf('=')+1);
                tmp=tmp.remove(0,tmp.indexOf('=')+1);
                tmp=tmp.remove(0,tmp.indexOf('=')+1);
                tmp.chop(2);
                dataUI.timeout=tmp.toInt();
                qDebug()<<tmp<<dataUI.timeout;

            }
            else
            {
                QStringList tmp;
                qDebug()<<readStr;
                tmp=readStr.split(',');
                int key=0;             //key 1 名字，2k 3type 4BIT
                for (int i=0;i<tmp.count();i++)
                {
                    QString Get=GetOriginalDataContent(tmp[i],key);
                    if(key==1)
                    {
                        dataUI.row[atLine-2].dataName=Get;
                    }
                    else if(key==2)
                    {
                        dataUI.row[atLine-2].k=Get.toFloat();
                    }
                    else if(key==3)
                    {
                        dataUI.row[atLine-2].type=Get;
                    }
                    else if(key==4)
                    {
                        dataUI.row[atLine-2].bit=Get.toInt();
                    }
                    else if(key==5)
                    {
                        if(Get.contains("0x"))
                        {
                            Get=Get.remove("0x");
                            bool ok;
                            dataUI.row[atLine-2].min=Get.toInt(&ok,16);
                        }
                        else if(Get.contains("0X"))
                        {
                            Get=Get.remove("0X");
                            bool ok;
                            dataUI.row[atLine-2].min=Get.toInt(&ok,16);
                        }
                        else
                        {
                            dataUI.row[atLine-2].min=Get.toFloat();
                        }
                    }
                    else if(key==6)
                    {
                        if(Get.contains("0x"))
                        {
                            Get=Get.remove("0x");
                            bool ok;
                            dataUI.row[atLine-2].max=Get.toInt(&ok,16);
                        }
                        else if(Get.contains("0X"))
                        {
                            Get=Get.remove("0X");
                            bool ok;
                            dataUI.row[atLine-2].max=Get.toInt(&ok,16);
                        }
                        else
                        {
                            dataUI.row[atLine-2].max=Get.toFloat();
                        }
                    }
                }
                qDebug()<<dataUI.row[0].dataName<<dataUI.row[0].type<<dataUI.row[0].k<<dataUI.row[0].bit<<dataUI.row[0].min<<dataUI.row[0].max;
            }
        }


        //这里初始化TableWidget表格对应的item。避免程序崩溃
        ui->spinBox->setValue(dataUI.start);
        ui->spinBox_2->setValue(dataUI.end-dataUI.start+1);
        registerStart=dataUI.start;
        registerSum=dataUI.end-dataUI.start+1;

        SetTableWigetByRow(dataUI.end-dataUI.start+1);
        InitTableWidgetItem(dataUI.end-dataUI.start+1);
        qDebug()<<dataUI.start<<dataUI.end;
        //显示名称
        //如果是32,64则跳过显示
        int registerCount=dataUI.end-dataUI.start+1;

        //显示寄存器号到表格
        for(int i=0;i<=registerCount-1;i++)
        {
            //获取表示寄存器序号的十进制字符串
            QString hex="";
            hex=hex+QString::number(i+dataUI.start,10);

            //设置寄存器序号字符串到表格
            QTableWidgetItem*item=GetItem(i,1);
            item->setText(hex);
            //设置序号到表格
            item=GetItem(i,0);
            item->setText(QString::number(i+1));
        }

        for(int i=0;i<=registerCount-1;i++)
        {
            QTableWidgetItem*item=GetItem(i,2);
            item->setText(dataUI.row[i].dataName);
            item=GetItem(i,4);
            item->setText(QString::number(dataUI.row[i].min));
            item=GetItem(i,5);
            item->setText(QString::number(dataUI.row[i].max));
            //跳过后续值
            //qDebug()<<"寄存器位数"<<dataUI.row[i].bit;
            if(dataUI.row[i].bit==16)
            {
                //不跳过
            }
            else if(dataUI.row[i].bit==32)
            {
                //先将跳过的行数置空
                for(int j=2;j<=6;j++)
                {
                    QTableWidgetItem* item=GetItem(i+1,j);
                    if(item!=nullptr)
                        item->setText("");
                }
                //跳过1行
                i++;
            }
            else if(dataUI.row[i].bit==64)
            {
                //跳过3行
                for(int j=2;j<=6;j++)
                {
                    QTableWidgetItem *item=GetItem(i+1,j);
                    if(item!=nullptr)
                        item->setText("");

                    item=GetItem(i+2,j);
                    if(item!=nullptr)
                        item->setText("");

                    item=GetItem(i+3,j);
                    if(item!=nullptr)
                        item->setText("");
                }
                i=i+3;
            }
        }
    }


}

void DockWidget2::ShowRecv(RecvBuf value, QByteArray sendData, QByteArray recvData, long)
{
    qDebug()<<"显示并存储接收到的值:ID="<<currentID;
    QString cmd;
    if(type==1)
        cmd="03";
    else if(type==2)
        cmd="04";
    ui->textEdit->setText("功能代码="+cmd+QString(",发送次数=%0,接收正确次数=%1，轮询时间=%2").arg(sendFrameCount).arg(recvFrameCount).arg(timeout));
    saveDateTime=QDateTime::currentDateTime();

    if(firstFlag)
    {
        firstFlag=false;
        GetSaveFileName();
        overflawFolderCount=GetWaringFolderCount();
    }

    //显示
    for(int i=0;i<=(value.bufDataCount/2)-1;i++)
    {
        //寄存器的内容为16bit数据，直接显示该数据
        if(dataUI.row[i].bit==16)
        {
            if(dataUI.row[i].type=="S")
            {
                //qDebug()<<"显示并存储接收到的值"<<__LINE__;
                Handle16bitStype(i,value,recvData);
                // qDebug()<<"显示并存储接收到的值"<<__LINE__;
            }
            else if(dataUI.row[i].type=="U")
            {
                Handle16bitUtype(i,value,recvData);
            }
            else if(dataUI.row[i].type=="X"||dataUI.row[i].type=="B")
            {
                Handle16bitXorBType(i,value,recvData);
            }
            else
            {
                Handle16bitStype(i,value,recvData);
            }
        }
        //两个16bit数组成1个32位数显示
        else if(dataUI.row[i].bit==32)
        {
            //i+1行置空
            for(int j=2;j<=6;j++)
            {
                QTableWidgetItem *item=GetItem(i+1,j);
                if(item!=nullptr)
                    item->setText("");

            }
            //合并字节
            uint32_t combine=0;
            if(i+1<=(value.bufDataCount/2)-1)
                combine=(value.recvBuf[i]&0xffff)|((value.recvBuf[i+1]<<16)&0xffff0000);
            else
                combine=value.recvBuf[i];
            //有符号数
            if(dataUI.row[i].type=="S")
            {
                Handle32bitSType(i,value,recvData,combine);
            }
            //无符号数
            else if(dataUI.row[i].type=="U")
            {
                Handle32bitUType(i,value,recvData,combine);
            }
            //十六进制数或二进制
            else if(dataUI.row[i].type=="X"||dataUI.row[i].type=="B")
            {
                Handle32bitXorBType(i,value,recvData,combine);
            }
            else
            {
                Handle32bitSType(i,value,recvData,combine);
            }
            //跳过下一行显示
            i=i+1;
        }
        //4个16bit合成1个64位的数
        else if(dataUI.row[i].bit==64)
        {
            //i+1，i+2,i+3行置空 0列shi2序号 1列是寄存器编号
            for(int j=2;j<=6;j++)
            {
                QTableWidgetItem *item=GetItem(i+1,j);
                if(item!=nullptr)
                    item->setText("");

                item=GetItem(i+2,j);
                if(item!=nullptr)
                    item->setText("");


                item=GetItem(i+3,j);
                if(item!=nullptr)
                    item->setText("");
            }
            //合并字节
            uint64_t combine=0;
            if(i+3<=(value.bufDataCount/2)-1)
                combine=(value.recvBuf[i]&0xffff)|((value.recvBuf[i+1]<<16)&0xffff0000)|(((uint64_t)value.recvBuf[i+2]<<32)&0xffff00000000)|(((uint64_t)value.recvBuf[i+3]<<48)&0xffff000000000000);
            else
                combine=value.recvBuf[i];
            //已加打印，合并字节无错
            // qDebug()<<value.recvBuf[i]<<value.recvBuf[i+1]<<value.recvBuf[i+2]<<value.recvBuf[i+3];
            if(dataUI.row[i].type=="S")//有符号数
            {
                Handle64bitSType(i,value,recvData,combine);
            }
            else if(dataUI.row[i].type=="U")
            {
                Handle64bitUType(i,value,recvData,combine);

            }
            else if(dataUI.row[i].type=="X"||dataUI.row[i].type=="B")
            {
                Handle64bitXorBType(i,value,recvData,combine);

            }
            //跳过3行
            i=i+3;
        }
        else
        {
            if(dataUI.row[i].type=="S")
            {
                Handle16bitStype(i,value,recvData);
            }
            else if(dataUI.row[i].type=="U")
            {
                Handle16bitUtype(i,value,recvData);
            }
            else if(dataUI.row[i].type=="X"||dataUI.row[i].type=="B")
            {
                Handle16bitXorBType(i,value,recvData);
            }
            else
            {
                Handle16bitStype(i,value,recvData);
            }
        }
    }


    SaveFile(sendData,recvData);
    qDebug()<<"显示结束";

}

void DockWidget2::ShowOverFlawTimes(int rows, int value)
{
    qDebug()<<rows<<value;
    if(value==6)
    {
        overFlawTime.row=&dataUI.row[rows];
        overFlawTime.show();
        overFlawTime.UpDate();
    }
}

void DockWidget2::ShowOverFlawTimes2(int rows, int value)
{
    qDebug()<<rows<<value;
    if(value==6)
    {
        overFlawTime.row=&dataUI.row[rows+32];
        overFlawTime.show();
        overFlawTime.UpDate();
    }
}

void DockWidget2::ShowOverFlawTimes3(int rows, int value)
{
    if(value==6)
    {
        overFlawTime.row=&dataUI.row[rows+64];
        overFlawTime.show();
        overFlawTime.UpDate();
    }
}

void DockWidget2::ShowOverFlawTimes4(int rows, int value)
{
    if(value==6)
    {
        overFlawTime.row=&dataUI.row[rows+96];
        overFlawTime.show();
        overFlawTime.UpDate();
    }
}


template<typename T>
void DockWidget2::DoShowEvents(T value)
{
  Q_UNUSED(value);
}

template<typename T>
void DockWidget2::BoundsChecking(T realValue, T min,T max,int i)
{
    QTableWidgetItem *item=GetItem(i,4);
    min=item->text().toUShort();
    item=GetItem(i,5);
    max=item->text().toUShort();

    if(realValue<min||realValue>max)
    {
        item=GetItem(i,3);
        item->setBackgroundColor(Qt::red);
        dataUI.row[i].overflowTimes++;
    }
    else
    {
        item=GetItem(i,3);
        item->setBackgroundColor(Qt::white);
    }
    item=GetItem(i,6);
    item->setText(QString::number(dataUI.row[i].overflowTimes));

}
